package com.bdqn.boot.controller;

import com.bdqn.boot.beans.User;
import com.bdqn.boot.beans.Users;
import com.bdqn.boot.constens.ProfixRedis;
import com.bdqn.boot.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author Hasee
 * @version 1.0
 * @className UserController
 * @description TODD
 * @date 2025/2/19 15:37
 */
@RestController
@CrossOrigin
public class UserController {
    @Autowired
    private UsersService usersService;
    @Autowired
    private RedisTemplate redisTemplate;
    //@RequestMapping(value = "/user",method = RequestMethod.GET)
    @GetMapping("/user")
    public List<Users> getUser(){
        return usersService.findAll();
    }
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Users user, HttpSession session){
        Map<String, Object> result = new HashMap<>();
        try {
            Users login = usersService.login(user.getUserName(), user.getPwd());
            if (login != null) {
                session.setAttribute("user", login); // 用户登录成功，存入 session
                //1.获取sessionid
                String token = session.getId();
                //存入rdais
                redisTemplate.opsForValue().set(ProfixRedis.TOKEN+token, login,30,
                        TimeUnit.MINUTES);
                System.out.println(ProfixRedis.TOKEN+token);
                result.put("token",token);
                result.put("success", true);
            } else {
                System.out.println("登录失败");
                result.put("success", false);
                result.put("message", "密码或者用户名错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "服务器错误，请稍后再试");
        }
        return result;
    }

    @PostMapping("/token/{token}")
    public Users token(@PathVariable String token){
        return (Users) redisTemplate.opsForValue().get(ProfixRedis.TOKEN+token);
    }

    @PostMapping("/logout/{token}")
    public Map<String,Object> logout(@PathVariable String token){
        Map<String,Object> result = new HashMap<>();
        try {
            redisTemplate.delete(ProfixRedis.TOKEN+token);
            result.put("success", true);
        }catch (Exception e){
            e.printStackTrace();
            result.put("success", false);
            result.put("msg","redis");
        }
        return result;
    }
}
